package org.jash.user.util

import android.content.Context
import android.hardware.biometrics.BiometricPrompt
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity

object FingerprintHelper {
    fun showBiometricPrompt(activity: FragmentActivity, onSuccess: () -> Unit, onError: (String) -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val promptInfo = BiometricPrompt.Builder(activity)
                .setTitle("指纹登录")
                .setSubtitle("请验证指纹以登录")
                .setNegativeButton("取消", ContextCompat.getMainExecutor(activity)) { _, _ ->
                    onError("用户取消")
                }
                .build()
            promptInfo.authenticate(android.os.CancellationSignal(), ContextCompat.getMainExecutor(activity), object : BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) {
                    onSuccess()
                }
                override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
                    onError(errString?.toString() ?: "验证失败")
                }
                override fun onAuthenticationFailed() {
                    onError("指纹不匹配")
                }
            })
        } else {
            onError("当前设备不支持指纹登录")
        }
    }
}
